iT邦幫忙

2024 iThome 鐵人賽

DAY 13
0
JavaScript

火箭通關JS30系列 第 13

JS30-13 - Slide in on Scroll

  • 分享至 

  • xImage
  •  

課程目的:

image.png

這次的內容是,當我們滾輪滑動到圖片的位置,圖片會自動彈入,這在很多網站是很常見的功能!
作品實作

本次功能實作重點:

  • 監聽滾輪動態
  • 當滾輪滑到對應的區塊滑入圖片邏輯
  • debounce邏輯

監聽滾輪動態

    const imges = document.querySelectorAll("img");
    window.addEventListener('scroll', debounce(scrollHandler));

imges選取網頁中的所有圖片元素

window.addEventListener('scroll', debounce(checkSlide)) 監聽'scroll' 狀態時執行函式scrollHandler

當滾輪滑到對應的區塊滑入圖片邏輯

   function scrollHandler() {
        const windowBotton = window.scrollY + window.innerHeight; //視窗最底的那條線
        imges.forEach((img) => {
          let imgMiddle = img.offsetTop + img.height / 2;
          if (imgMiddle <= windowBotton) {
            img.classList.add("active");
          } else {
            img.classList.remove("active");
          }
        });
      }

windowBotton頁面已經滾動的垂直距離 + 當前視窗的可視高度,代表網頁滑動的總長

imgMiddle 為img頁面中的高度 + img本身的高度/2代表每張圖片的中線在網頁中的高度

if (imgMiddle <= windowBotton) 如果windowBotton 滑動的距離超過imgMiddle Class增加active特效,反之則消除

debounce邏輯

  //當20毫秒內沒有動作則執行
  function debounce(func, wait = 20, immediate = true) {
        var timeout;
        return function () {
          var context = this,
            args = arguments;
          var later = function () {
            timeout = null;
            if (!immediate) func.apply(context, args);
          };
          var callNow = immediate && !timeout;
          clearTimeout(timeout);
          timeout = setTimeout(later, wait);
          if (callNow) func.apply(context, args);
        };
      }

function debounce(func, wait = 20, immediate = true)

這個函式的邏輯是說,當我們觸發一次函式時,會先用 clearTimeout(timeout) 清除前面的計時器並且重新設定 setTimeout(later, wait);

func 為我們要帶入的函式

wait 代表等待的時間

immediate 決定是否應立即執行 func,默認值為 true(立即執行)

later當我們等待了20毫秒後賦值timeout = null;

if (callNow) 如果滿足條件immediate為true,!timeout為false則執行func.apply(context, args)

導讀文件以及學習資源

JS30
[ Alex 宅幹嘛 ] 👨‍💻 深入淺出 Javascript30 快速導覽 | Day 13:Slide in on Scroll


上一篇
JS30-12 - Key Sequence Detection
下一篇
JS30-14-JavaScript-References-VS-Copying
系列文
火箭通關JS3014
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言